package cmd

import (
	"fmt"
	"github.com/spf13/cobra"
	"migration-tool/common"
	"migration-tool/schedule"
	"os"
	"time"
)

var DryRun bool
var Force bool
var Remove bool
var Increment bool

func init() {
	rootCmd.AddCommand(exportCommand)
	rootCmd.AddCommand(importCommand)

	exportCommand.PersistentFlags().BoolVar(&DryRun, "dry-run", false, "模拟执行，来查看模拟导出的仓库")
	exportCommand.PersistentFlags().BoolVar(&Force, "force", false, "不使用之前的任务进度")
	exportCommand.PersistentFlags().BoolVar(&Increment, "increment", false, "执行增量导出")
	exportCommand.PersistentFlags().BoolVar(&Remove, "remove", false, "本次执行，仅删除增量导出的结果")

	importCommand.PersistentFlags().BoolVar(&DryRun, "dry-run", false, "模拟执行，来查看模拟导出的仓库")
	importCommand.PersistentFlags().BoolVar(&Force, "force", false, "不使用之前的任务进度")
	importCommand.PersistentFlags().BoolVar(&Increment, "increment", false, "执行增量导入")
}

var exportCommand = &cobra.Command{
	Use:   "export [--config=filepath] [--dry-run] [--force] [--increment] [--remove]",
	Short: "执行导出操作，由increment参数配置是否执行增量，配置文件中timeStamp不生效",
	Run: func(cmd *cobra.Command, args []string) {
		if ConfigFilePath == "" {
			ConfigFilePath = common.GlobalDefaultConfigPath
		}
		coordinatorArgs := schedule.CoordinatorArgs{
			ConfigPath:    ConfigFilePath,
			Export:        true,
			IncrementFlag: Increment,
			UseProgress:   !Force,
		}

		c, err := schedule.MakeCoordinator(coordinatorArgs)
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}

		if DryRun {
			err = c.DryRun()
			if err != nil {
				c.RecordLog("DryRun过程出现错误", err)
			} else {
				c.RecordLog("DryRun执行完成", nil)
			}
			return
		}

		if Increment && Remove {
			err = c.RemoveIncrement()
			if err != nil {
				c.RecordLog("删除增量导出文件出现错误", err)
			} else {
				c.RecordLog("删除增量导出文件成功", nil)
			}
			return
		}

		if c != nil {
			err := c.Start()
			if err != nil {
				return
			}
			for !c.Done() {
				time.Sleep(time.Second * 5)
			}
			if Increment {
				c.RecordLog("[增量导出]工作完成", nil)
			} else {
				c.RecordLog("[导出]工作完成", nil)
			}
		}
	},
}

var importCommand = &cobra.Command{
	Use:   "import [--config=filepath] [--dry-run] [--force] [--increment]",
	Short: "执行导入操作，由increment参数配置是否执行增量",
	Run: func(cmd *cobra.Command, args []string) {
		if ConfigFilePath == "" {
			ConfigFilePath = common.GlobalDefaultConfigPath
		}
		coordinatorArgs := schedule.CoordinatorArgs{
			ConfigPath:    ConfigFilePath,
			Export:        false,
			IncrementFlag: Increment,
			UseProgress:   !Force,
		}

		c, err := schedule.MakeCoordinator(coordinatorArgs)
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}

		if DryRun {
			err = c.DryRun()
			if err != nil {
				c.RecordLog("DryRun过程出现错误", err)
			} else {
				c.RecordLog("DryRun执行完成", nil)
			}
			return
		}

		if c != nil {
			err := c.Start()
			if err != nil {
				return
			}
			for !c.Done() {
				time.Sleep(time.Second * 5)
			}

			if Increment {
				c.RecordLog("[增量导入]工作完成", nil)

			} else {
				c.RecordLog("[导入]工作完成", nil)
			}
		}
	},
}
